<?php

namespace kdapi;


use app\common\model\OrderReceiptModel;

/**
 * Class KdApiPrint
 * @package kdapi
 * @description    先通过快递鸟电子面单接口提交电子面单后，再组装POST表单调用快递鸟批量打印接口页面
 */
class Eprint extends Api
{
    const API_URL = 'http://www.kdniao.com/External/PrintOrder.aspx';
    const IP_SERVICE_URL = 'http://www.kdniao.com/External/GetIp.aspx';

    public function build_form($receipt_ids, $port_name = '')
    {
        $orders = OrderReceiptModel::where('id', 'in', $receipt_ids)->select();
        $data = [];
        foreach ($orders as $order) {
            if (!empty($order->delivery_no) && !empty($order->delivery_code) && $order->delivery_type == 3) {
                $data[] = [
                    'OrderCode' => $order['self_order_no'],
                    'PortName'  => $port_name
                ];
            }
        }
        if (empty($data)) {
            return false;
        }

        $request_data = json_encode($data);
        $request_data_encode = urlencode(json_encode($data));
//        OrderCode:需要打印的订单号，和调用快递鸟电子面单的订单号一致，PortName：本地打印机名称，请参考使用手册设置打印机名称。支持多打印机同时打印。
//        $request_data = '[{"OrderCode":"20190718153830301435","PortName":"print1"}]';

        $data_sign = $this->encrypt($this->get_ip() . $request_data, self::AppKey);
//        $data_sign = $this->encrypt('115.60.19.170' . $request_data, self::AppKey);
        //是否预览，0-不预览 1-预览
        $is_priview = 0;

        //组装表单
        $form = '<form id="form" stype="display: block" method="POST" action="' . self::API_URL . '">
                    <input type="text" name="RequestData" value=\'' . $request_data . '\'>
                    <input type="text" name="EBusinessID" value="' . self::EBusinessID . '">
                    <input type="text" name="DataSign" value="' . $data_sign . '">
                    <input type="text" name="IsPriview" value="' . $is_priview . '"></form>
                <script>form.submit();</script>';
        echo $form;
    }

    /**
     * 获取客户端IP(非用户服务器IP)
     * 批量打印dmeo中GetIp()获取到的IP是否和外网IP（连接打印机那台电脑的外网ip，可通过百度搜索ip38查看）一致，若不一致您可以改写demo中GetIp()的方法，直至一致为止。
     * @return 客户端IP
     */
    protected function get_ip()
    {
        //获取客户端IP
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $ip = getenv('REMOTE_ADDR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }

        if (!$ip || $this->is_private_ip($ip)) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, self::IP_SERVICE_URL);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($ch);
            return $output;
        } else {
            return $ip;
        }
    }

    /**
     * 判断是否为内网IP
     * @param ip IP
     * @return 是否内网IP
     */
    protected function is_private_ip($ip)
    {
        return !filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
    }

}